/**
 * 价格体系 - 主界面
 * 
 * @author PSI
 * @copyright 2015 - present
 * @license GPL v3
 */
PCL.define("PSI.SLN0001.Goods.PriceSystemMainForm", {
  extend: "PSI.AFX.Form.MainForm",

  /**
   * 初始化组件
   * 
   * @override
   */
  initComponent() {
    const me = this;

    PCL.apply(me, {
      border: 0,
      layout: "border",
      tbar: [{
        iconCls: "PSI-tb-new",
        text: "新建价格",
        ...PSI.Const.BTN_STYLE,
        handler: me._onAddPrice,
        scope: me
      }, {
        text: "编辑价格",
        ...PSI.Const.BTN_STYLE,
        handler: me._onEditPrice,
        scope: me
      }, {
        text: "删除价格",
        ...PSI.Const.BTN_STYLE,
        handler: me._onDeletePrice,
        scope: me
      }, "-", {
        iconCls: "PSI-tb-help",
        text: "指南",
        ...PSI.Const.BTN_STYLE,
        handler() {
          me.focus();
          const url = me.URL("/Home/Help/index?t=priceSystem")
          window.open(url);
        }
      }, "-", {
        iconCls: "PSI-tb-close",
        text: "关闭",
        ...PSI.Const.BTN_STYLE,
        handler() {
          me.focus();
          me.closeWindow();
        }
      }].concat(me.getShortcutCmp()),
      items: [{
        region: "north",
        height: 55,
        border: 0,
        bodyPadding: "0 20 0 20",
        html: "<h2 style='color:#595959;display:inline-block'>价格体系</h2>&nbsp;&nbsp;<span style='color:#8c8c8c'>基础数据</span>",
      }, {
        region: "center",
        xtype: "panel",
        layout: "fit",
        bodyPadding: "0 20 5 15",
        border: 0,
        items: [me.getMainGrid()]
      }]
    });

    me.callParent(arguments);

    me.freshGrid();
  },

  /**
   * 快捷访问
   * 
   * @private
   */
  getShortcutCmp() {
    return ["->",
      {
        cls: "PSI-Shortcut-Cmp",
        labelWidth: 0,
        emptyText: "快捷访问",
        xtype: "psi_mainmenushortcutfield",
        width: 90
      }
    ];
  },

  /**
   * 新增价格
   * 
   * @private
   */
  _onAddPrice() {
    const me = this;

    const form = PCL.create("PSI.SLN0001.Goods.PriceSystemEditForm", {
      renderTo: PSI.Const.RENDER_TO(),
      parentForm: me
    });

    form.show();
  },

  /**
   * 编辑价格
   * 
   * @private
   */
  _onEditPrice() {
    const me = this;

    const item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("请选择要编辑的价格");
      return;
    }

    const price = item[0];

    const form = PCL.create("PSI.SLN0001.Goods.PriceSystemEditForm", {
      renderTo: PSI.Const.RENDER_TO(),
      parentForm: me,
      entity: price
    });

    form.show();
  },

  /**
   * 删除价格
   * 
   * @private
   */
  _onDeletePrice() {
    const me = this;
    const item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("请选择要删除的价格");
      return;
    }

    const price = item[0];
    const info = `请确认是否删除价格 <span style='color:red'>${price.get("name")}</span> ?`;

    const store = me.getMainGrid().getStore();
    let index = store.findExact("id", price.get("id"));
    index--;
    let preIndex = null;
    const preItem = store.getAt(index);
    if (preItem) {
      preIndex = preItem.get("id");
    }

    const funcConfirm = () => {
      const el = PCL.getBody();
      el.mask(PSI.Const.LOADING);
      const r = {
        url: me.URL("SLN0001/Goods/deletePriceSystem"),
        params: {
          id: price.get("id")
        },
        callback(options, success, response) {
          el.unmask();
          if (success) {
            const data = me.decodeJSON(response.responseText);
            if (data.success) {
              me.tip("成功完成删除操作", true);
              me.freshGrid(preIndex);
            } else {
              me.showInfo(data.msg);
            }
          } else {
            me.showInfo("网络错误");
          }
        }
      };
      me.ajax(r);
    };

    me.confirm(info, funcConfirm);
  },

  /**
   * 刷新Grid
   * 
   * @private
   */
  freshGrid(id) {
    const me = this;
    const grid = me.getMainGrid();

    const el = grid.getEl() || PCL.getBody();
    el.mask(PSI.Const.LOADING);
    me.ajax({
      url: me.URL("SLN0001/Goods/priceSystemList"),
      callback(options, success, response) {
        const store = grid.getStore();

        store.removeAll();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          store.add(data);
          if (id) {
            const r = store.findExact("id", id);
            if (r != -1) {
              grid.getSelectionModel().select(r);
            } else {
              grid.getSelectionModel().select(0);
            }

          }
        }

        el.unmask();
      }
    });
  },

  /**
   * @private
   */
  getMainGrid() {
    const me = this;

    if (me._mainGrid) {
      return me._mainGrid;
    }

    const modelName = me.buildModelName(me, "GoodsPriceSystem");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "name", "factor"]
    });

    me._mainGrid = PCL.create("PCL.grid.Panel", {
      cls: "PSI-FC",
      border: 1,
      columnLines: true,
      columns: {
        defaults: {
          menuDisabled: true,
          sortable: false
        },
        items: [{
          header: "#",
          xtype: "rownumberer",
          width: 40
        }, {
          header: "价格名称",
          dataIndex: "name",
          width: 400
        }, {
          header: "销售基准价的倍数",
          width: 140,
          dataIndex: "factor",
          align: "right"
        }]
      },
      store: PCL.create("PCL.data.Store", {
        model: modelName,
        autoLoad: false,
        data: []
      }),
      listeners: {
        itemdblclick: {
          fn: me._onEditPrice,
          scope: me
        }
      }
    });

    return me._mainGrid;
  }
});
